﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RESP_IIWaterAssessment
{
    public partial class IndikatorsForm : Form
    {
        public IndikatorsForm()
        {
            InitializeComponent();
        }

        int regID, year, month;
        tb_indicator Indicator;

        private void IndikatorsForm_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";
            cbRegion.SelectedIndex = -1;
            cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);


            string[] month;
            if (InformationClass.Lang)
                month = new string[] { "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" };
            else
                month = new string[] { "Январ", "Феврал", "Март", "Апрел", "Май", "Июн", "Июл", "Август", "Сентябр", "Октябр", "Ноябр", "Декабр" };

            for (int i = 1; i <= 12; i++)
            {
                var m = new
                {
                    ID = i,
                    Name = month[i - 1]
                };
                cbMonth.Items.Add(m);
            }
            cbMonth.DisplayMember = "Name";
            cbMonth.ValueMember = "ID";

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }
            cbMonth.SelectedIndex = cbMonth.FindStringExact(month[DateTime.Now.Month - 1]);
            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());
            this.year = Convert.ToInt32(cbYear.Text);
            this.month = cbMonth.SelectedIndex + 1;
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                ShowIndicators(regID, month, year);
            }
            else
                regID = 0;
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (regID > 0 && cbYear.SelectedIndex >= 0)
            {
                year = Convert.ToInt32(cbYear.Text);
                ShowIndicators(regID, month, year);
            }
        }

        private void cbMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (regID > 0 && cbMonth.SelectedIndex >= 0)
            {
                month = cbMonth.SelectedIndex + 1;
                ShowIndicators(regID, month, year);
            }
        }

        private void ShowIndicators(int regID, int month, int year)
        {
            Indicator = DBClass.Indicators
                .Where(wh => wh.RegionID == regID && wh.Date == new DateTime(year, month, 1))
                .SingleOrDefault();
            if (Indicator != null)
            {
                tbSatisfiedWaterUsers.Text = Indicator.SatisfiedWaterUsers.Value.ToString();
                tbProductivitySeed.Text = Indicator.ProductivitySeed.Value.ToString();
                tbProductivityCulture.Text = Indicator.ProductivityCulture.Value.ToString();
                tbProductivityCotton.Text = Indicator.ProductivityCotton.Value.ToString();
                tbOffFarmQuantity.Text = Indicator.OffFarmQuantity.Value.ToString();
                tbOffFarmArea.Text = Indicator.OffFarmArea.Value.ToString();
                tbInterFarmQuantity.Text = Indicator.InterFarmQuantity.Value.ToString();
                tbInterFarmArea.Text = Indicator.InterFarmArea.Value.ToString();
                tbImplementationOFP.Text = Indicator.ImplementationOFP.Value.ToString();
                tbFarmersWithTrays.Text = Indicator.FarmersWithTrays.Value.ToString();
                tbFarmersOverQuota.Text = Indicator.FarmersOverQuota.Value.ToString();
                tbAverageIncome.Text = Indicator.AverageIncome.Value.ToString();
            }
            else
            {
                tbAverageIncome.Text = tbFarmersOverQuota.Text = tbFarmersWithTrays.Text = tbImplementationOFP.Text =
                    tbInterFarmArea.Text = tbInterFarmQuantity.Text = tbOffFarmArea.Text = tbOffFarmQuantity.Text =
                    tbProductivityCotton.Text = tbProductivityCulture.Text = tbProductivitySeed.Text = tbSatisfiedWaterUsers.Text = string.Empty;
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {

            if (regID > 0 && month > 0 && year > 0)
            {
                int offFarmQuantity, interFarmQuantity, satisfiedWaterUsers;
                decimal offFarmArea, interFarmArea, productivityCulture, productivityCotton, productivitySeed,
                    implementationOFP, farmersWithTrays, farmersOverQuota, averageIncome;

                bool correct = Int32.TryParse(tbOffFarmQuantity.Text, out offFarmQuantity);
                correct &= Int32.TryParse(tbInterFarmQuantity.Text, out interFarmQuantity);
                correct &= Int32.TryParse(tbSatisfiedWaterUsers.Text, out satisfiedWaterUsers);

                correct &= tbOffFarmArea.Text.GetDecimalOrDefault(out offFarmArea);
                correct &= tbInterFarmArea.Text.GetDecimalOrDefault(out interFarmArea);
                correct &= tbProductivityCulture.Text.GetDecimalOrDefault(out productivityCulture);
                correct &= tbProductivityCotton.Text.GetDecimalOrDefault(out productivityCotton);
                correct &= tbProductivitySeed.Text.GetDecimalOrDefault(out productivitySeed);
                correct &= tbImplementationOFP.Text.GetDecimalOrDefault(out implementationOFP);
                correct &= tbFarmersWithTrays.Text.GetDecimalOrDefault(out farmersWithTrays);
                correct &= tbFarmersOverQuota.Text.GetDecimalOrDefault(out farmersOverQuota);
                correct &= tbAverageIncome.Text.GetDecimalOrDefault(out averageIncome);

                string msg = InformationClass.Lang ? "Заполненны не все поля. Не верно заполненные поля и оставленные без значений будут заполненны нулями.\nПродолжить?" : "Барча сатрлар тўлдирилмаган. Нотўғри тўлдирилган ҳамда тўлдирилмаган сатрлар ноллар билан тўлдирилади. Давом эттирилсинми? ";

                if (!correct)
                {
                    if (MessageBox.Show(msg, "Винимание", MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        return;
                    }
                }

                if (Indicator != null)
                {
                    Indicator.AverageIncome = averageIncome;
                    Indicator.FarmersOverQuota = farmersOverQuota;
                    Indicator.FarmersWithTrays = farmersWithTrays;
                    Indicator.ImplementationOFP = implementationOFP;
                    Indicator.InterFarmArea = interFarmArea;
                    Indicator.InterFarmQuantity = interFarmQuantity;
                    Indicator.OffFarmArea = offFarmArea;
                    Indicator.OffFarmQuantity = offFarmQuantity;
                    Indicator.ProductivityCotton = productivityCotton;
                    Indicator.ProductivityCulture = productivityCulture;
                    Indicator.ProductivitySeed = productivitySeed;
                    Indicator.SatisfiedWaterUsers = satisfiedWaterUsers;
                }
                else
                {
                    Indicator = new tb_indicator
                    {
                        AverageIncome = averageIncome,
                        FarmersOverQuota = farmersOverQuota,
                        FarmersWithTrays = farmersWithTrays,
                        ImplementationOFP = implementationOFP,
                        Date = new DateTime(year, month, 1),
                        InterFarmArea = interFarmArea,
                        InterFarmQuantity = interFarmQuantity,
                        OffFarmArea = offFarmArea,
                        OffFarmQuantity = offFarmQuantity,
                        ProductivityCotton = productivityCotton,
                        ProductivityCulture = productivityCulture,
                        ProductivitySeed = productivitySeed,
                        RegionID = regID,
                        SatisfiedWaterUsers = satisfiedWaterUsers
                    };
                    DBClass.Indicators.InsertOnSubmit(Indicator);
                }
                try
                {
                    DBClass.RESPContext.SubmitChanges();

                    MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                }
                catch
                {
                    MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                    DBClass.Indicators.DeleteOnSubmit(Indicator);
                    DBClass.RESPContext.SubmitChanges();
                }
            }
            else
            {
                if (InformationClass.Lang)
                    MessageBox.Show("Не выбран район или не указанна дата");
                else
                    MessageBox.Show("Туман танланмаган ёки сана кўрсатилмаган");
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
